//
//  XPlanDetailsViewController.m
//  iPlan
//
//  Created by 侯伟 on 2021/8/29.
//

#import "XPlanDetailsViewController.h"
#import "XPlanEditViewController.h"
#import "XPlanRecordViewController.h"
static UIImage * btnImage() {

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(60, 60), NO, 0);
    
    CGContextRef gc = UIGraphicsGetCurrentContext();
    //创建CGMutablePathRef
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddArc(path, NULL, 30, 30, 5, 0, M_PI*2, YES);
    //将CGMutablePathRef添加到当前Context内
    CGContextAddPath(gc, path);
    //设置绘图属性
    [COLOR_THEME_A setStroke];
    CGContextSetLineWidth(gc, 10);
    //执行绘画
    CGContextStrokePath(gc);
    
    //创建CGMutablePathRef
    CGMutablePathRef path2 = CGPathCreateMutable();
    CGPathAddArc(path2, NULL, 30, 30, 25, 0, M_PI*2, YES);
    //将CGMutablePathRef添加到当前Context内
    CGContextAddPath(gc, path2);
    
    //设置绘图属性
    [COLOR_THEME_A setStroke];
    CGContextSetLineWidth(gc, 5);
    //执行绘画
    CGContextStrokePath(gc);
    
    CGPathRelease(path);
    CGPathRelease(path2);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@interface XPlanDetailsViewController ()<UITextViewDelegate>

///// x
//@property(nonatomic,weak)UIButton* modify;


@property(nonatomic,strong)MyLinearLayout *contentLayout;

/// 名称
@property(nonatomic,strong)UILabel* nameLb;

/// 数量
@property(nonatomic,strong)UILabel* countLb;

/// 占位文本
@property(nonatomic,strong)UILabel* deacLb;

/// 字数
@property(nonatomic,strong)UILabel* numLb;

/// x
@property(nonatomic,strong)UIButton* clockBtn;


@property(nonatomic,strong)MyLinearLayout *bottomLayout;

/// x
@property(nonatomic,strong)UIButton* resetBtn;

/// x
@property(nonatomic,strong)UIButton* historyBtn;

/// x
@property(nonatomic,strong)UIButton* modeifyCountBtn;

@end

@implementation XPlanDetailsViewController


- (void)loadView{
    [super loadView];
    // 线性布局
    self.view.backgroundColor = COLOR_WHITE;
    
    MyLinearLayout *rootLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    rootLayout.myMargin = 0;
    [self.view addSubview:rootLayout];

    // 线性布局
    MyLinearLayout *contentLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    contentLayout.myMargin = 0;
    contentLayout.weight = 1.0;
    [rootLayout addSubview:contentLayout];
    _contentLayout = contentLayout;
    
    //底部
    MyLinearLayout *bottomLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Horz)];
    bottomLayout.myHeight = IPHONE_TAB_BAR_HEIGHT;
    bottomLayout.myMargin = 0;
    bottomLayout.padding = UIEdgeInsetsMake(0, IPHONE_BOTTOM_SAFEINSET, 0, 0);
    bottomLayout.gravity = MyGravity_Horz_Fill;
    [rootLayout addSubview:bottomLayout];
    _bottomLayout = bottomLayout;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNavBar];
    
    [self setupViews];
    
    [self updateViews];
}

- (void)setupNavBar{
    
    self.navigationItem.title = @"手动计数";

    UIBarButtonItem* modidyItem = [[UIBarButtonItem alloc] initWithTitle:@"修改" style:(UIBarButtonItemStylePlain) target:self action:@selector(modidyClicked:)];
    self.navigationItem.rightBarButtonItem = modidyItem;
}

- (void)setupViews{
    
    UILabel* nameLb = [UILabel lableWithFont:FONTMID_FIT(17) color:COLOR_BLACK_DARK text:NULL];
    nameLb.numberOfLines = 2;
    nameLb.textAlignment = NSTextAlignmentCenter;
    nameLb.myCenterX = 0;
    nameLb.myTop = 32;
    nameLb.myHeight = MyLayoutSize.wrap;
    nameLb.myWidth = PX(200);
    [self.contentLayout addSubview:nameLb];
    _nameLb = nameLb;
    

    UILabel* countLb = [UILabel lableWithFont:FONTMID_FIT(14) color:COLOR_GRAY_BASE text:NULL];
    countLb.textAlignment = NSTextAlignmentCenter;
    countLb.myCenterX = 0;
    countLb.myTop = 16;
    [self.contentLayout addSubview:countLb];
    _countLb = countLb;
    
    
    UILabel* numLb = [UILabel lableWithFont:FONTBOLD_FIT(20) color:COLOR_THEME_A text:NULL];
    numLb.textAlignment = NSTextAlignmentCenter;
    numLb.myCenterX = 0;
    numLb.myTop = 40;
    [self.contentLayout addSubview:numLb];
    _numLb = numLb;
    
    
    UIButton* clockBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [clockBtn setBackgroundImage:btnImage() forState:UIControlStateNormal];
    [clockBtn addTarget:self action:@selector(clockClicked:) forControlEvents:UIControlEventTouchUpInside];
    clockBtn.mySize = CGSizeMake(PX(60), PX(60));
    clockBtn.myCenterX = 0;
    clockBtn.myTop = 100;
    [self.contentLayout addSubview:clockBtn];
    
    [self addBottomBtn:@"重置计数" sel:@selector(resetClicked:)];
    [self addBottomBtn:@"计数记录" sel:@selector(historyClicked:)];
    [self addBottomBtn:@"修改计数" sel:@selector(manualModifyClicked:)];
}

- (void)addBottomBtn:(NSString*)title sel:(SEL)sel{
    
    UIButton* resetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [resetBtn setTitle:title forState:UIControlStateNormal];
    [resetBtn setTitleColor:COLOR_BLACK_DARK forState:UIControlStateNormal];
    [resetBtn addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    resetBtn.titleLabel.font = FONT(14);
    resetBtn.myMargin = 0;
    [self.bottomLayout addSubview:resetBtn];
}

- (void)updateViews{
    
    self.nameLb.text = self.model.name;
    [self.nameLb sizeToFit];
    
    NSString* time;
    switch (self.dateType) {
        case ADateType_Day:
            time = @"日";
            break;
        case ADateType_Week:
            time = @"周";
            break;
        case ADateType_Month:
            time = @"月";
            break;
        case ADateType_Year:
            time = @"年";
            break;
        default:
            break;
    }
    
    RLMResults* clocks = [XPlanDate objectsWhere:@"planId = %ld and time = %@",self.model.id,[[NSDate date] stringYearMonthDay]];
    NSInteger count = 0;
    if(clocks.count){
        XPlanDate* clock = clocks.firstObject;
        count = clock.count;
    }
    
    NSString* countStr = [NSString stringWithFormat:@"已完成 %ld / 每%@目标 %ld",count,time,self.model.planCount];
    self.countLb.text = countStr;
    [self.countLb sizeToFit];
    
    if(count >= self.model.planCount){
        self.countLb.textColor = COLOR_RED;
    }
    
    NSString* numStr = [NSString stringWithFormat:@"%ld",count];
    self.numLb.text = numStr;
    [self.numLb sizeToFit];
}

#pragma mark  --- action
///修改
- (void)modidyClicked:(UIButton*)sender{
    
    XPlanEditViewController* editController = [XPlanEditViewController new];
    editController.operation = EditOperation_Edit;
    editController.dateType = self.dateType;
    editController.model = self.model;
    editController.editBlock = ^(id  _Nullable obj, EditOperation operation) {
        
        self.model = obj;
        
        [self updateViews];
    };
    [UIViewController showViewController:editController animated:YES];
}

///打卡
- (void)clockClicked:(UIButton*)sender{
    
    RLMResults* clocks = [XPlanDate objectsWhere:@"planId = %ld and time = %@",self.model.id,[[NSDate date] stringYearMonthDay]];
    if(clocks.count){
        XPlanDate* clock = clocks.firstObject;
        [[RLMRealm defaultRealm] beginWriteTransaction];
        
        clock.count += 1;
        [[RLMRealm defaultRealm] addOrUpdateObject:clock];
        
        [[RLMRealm defaultRealm] commitWriteTransaction];
    }else{
        XPlanDate* clock = [XPlanDate new];
        clock.count = 1;
        clock.time = [[NSDate date] stringYearMonthDay];
        clock.planId = self.model.id;
        
        [[RLMRealm defaultRealm] beginWriteTransaction];
        [[RLMRealm defaultRealm] addOrUpdateObject:clock];
        [[RLMRealm defaultRealm] commitWriteTransaction];
    }
    
    [self updateViews];
}

///重置计数
- (void)resetClicked:(UIButton*)sender{
    
    RLMResults* clocks = [XPlanDate objectsWhere:@"planId = %ld and time = %@",self.model.id,[[NSDate date] stringYearMonthDay]];
    
    if(clocks.count){
        XPlanDate* clock = clocks.firstObject;
        [[RLMRealm defaultRealm] beginWriteTransaction];
        clock.count = 0;
        [[RLMRealm defaultRealm] addOrUpdateObject:clock];
        
        [[RLMRealm defaultRealm] commitWriteTransaction];
    }
    
    [self updateViews];
}

///历史记录
- (void)historyClicked:(UIButton*)sender{
    XPlanRecordViewController* history = [XPlanRecordViewController new];
    history.model = self.model;
    [UIViewController showViewController:history animated:YES];
}

///手动修改
- (void)manualModifyClicked:(UIButton*)sender{
    
    RLMResults* clocks = [XPlanDate objectsWhere:@"planId = %ld and time = %@",self.model.id,[[NSDate date] stringYearMonthDay]];
    
    NSInteger count = 0;
    if(clocks.count){
        XPlanDate* clock = clocks.firstObject;
        count = clock.count;
    }
    
    
    UIAlertController* alertController = [UIAlertController alertControllerWithTitle:@"手动计数" message:@"请谨慎修改哟!" preferredStyle:(UIAlertControllerStyleAlert)];
    
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = [NSString stringWithFormat:@"%ld",count];
        textField.placeholder = @"输入计数";
        textField.keyboardType = UIKeyboardTypeDecimalPad;
    }];
    UIAlertAction* sure = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        NSString* text = alertController.textFields.firstObject.text;
   
        if(clocks.count){
            XPlanDate* clock = clocks.firstObject;
            [[RLMRealm defaultRealm] beginWriteTransaction];
            
            clock.count = [text integerValue];
            [[RLMRealm defaultRealm] addOrUpdateObject:clock];
            
            [[RLMRealm defaultRealm] commitWriteTransaction];
        }else{
            XPlanDate* clock = [XPlanDate new];
            clock.count = [text integerValue];
            clock.time = [[NSDate date] stringYearMonthDay];
            clock.planId = self.model.id;
            
            [[RLMRealm defaultRealm] beginWriteTransaction];
            [[RLMRealm defaultRealm] addOrUpdateObject:clock];
            [[RLMRealm defaultRealm] commitWriteTransaction];
        }
        
        [self updateViews];
    }];
    UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {

    }];
    [alertController addAction:cancel];
    [alertController addAction:sure];
    
    [self presentViewController:alertController animated:YES completion:NULL];
}

@end
